const jwt = require('jsonwebtoken');
var access = "accessToken"//短token(访问令牌)密钥
var refresh = 'refreshToken'//长token(刷新令牌)密钥
const verifyAccessToken = (req, res, next) => {//验证访问令牌中间件
    if (req.path === '/login' || req.path === '/register' || req.path === '/refreshtoken'
        || req.path === '/loginByPhone') { return next() }//设置白名单
    let accessToken = req.headers['authorization'] ?
        req.headers['authorization'].split(' ')[1] : null;//获取请求头中访问令牌
    if (!accessToken) {
        return res.status(401).json({ message: 'Unauthorized' });
    }//如果没有令牌 则返回401 重新登录
    try {//验证访问令牌 过期则返回403 前端接收到403后会访问刷新令牌接口
        const decoded = jwt.verify(accessToken, access);
        req.user = decoded;
        next();
    } catch (err) {
        console.log(err);
        return res.status(403).json({ message: 'Invalid token' });
    }
}
module.exports = { verifyAccessToken }